<template>
  <div class="app-container answer3" style="display: flex; justify-content: center; padding-top: 37px">
    <el-form :model="queryParam" ref="queryForm" :rules="rules"  style="text-align: center;  width: 40%;" label-width="122px">
      <el-row style="margin: auto; width: 100%; text-align: center; height: 42px;">
          <h1 style="display: inline-block; margin-top: -4px; text-align: center; color: #8b836c; font-size: 1.3rem; letter-spacing: 1px; font-family: serif;">下载培训记录</h1>
      </el-row>
      <el-row>
        <el-form-item label="培训员工：">
          <el-select v-model="queryParam.userId" filterable placeholder="请选择（或输入）员工姓名" clearable @change="qryRelaDeparts">
            <el-option
              v-for="item in relaEmpList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              :title="item.name">
              <span>{{ item.name }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="对应部门：">
          <el-select v-model="queryParam.deptId"  placeholder="请选择（或输入）部门名称" :disabled="diableDept" clearable>
            <el-option
              v-for="item in relaDeptList"
              :key="item.id"
              :label="item.name"
              :value="item.id"
              :title="item.name">
              <span>{{ item.name }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="建档日期：">
          <el-date-picker v-model="queryParam.createDate" type="date" value-format="yyyy-MM-dd" placeholder="请选择建档日期" />
        </el-form-item>
        <el-form-item label="发布时间：" prop="teacherTime" required>
          <el-date-picker v-model="queryParam.teacherTime" value-format="yyyy-MM-dd" type="daterange"
                          range-separator="至" start-placeholder="开始日期" end-placeholder="结束日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="考试类型：" prop="category">
          <el-autocomplete
            ref="categoryAutocompleteRef"
            v-model="queryParam.category"
            class="inline-input"
            :fetch-suggestions="categoryQuerySearch"
            placeholder="请选择（或输入）考试类型"
            style="cursor: pointer"
            @keyup.native="categoryKeyup($event)"
            @focus="categoryAutocomplete = true"
            @blur="categoryAutocomplete = false"
            clearable
            @clear="categorySearchHandle"
          >
            <template slot-scope="{ item }">
              <a :title="item.value" style="text-decoration:none">{{ item.value }}</a>
            </template>
          </el-autocomplete>
        </el-form-item>
      </el-row>
      <el-form style="margin-top: 24px; display: flex; justify-content: center;">
        <el-button type="primary" @click="submitForm" :disabled="disabledBtn">下载培训记录</el-button>
      </el-form>
    </el-form>
  </div>
</template>

<script>

import {mapActions} from 'vuex'
import Pagination from '@/components/Pagination'
import userApi from '@/api/user'
import ansApi from '@/api/examPaperAnwser'
import taskApi from "@/api/task";

export default {
  components: { Pagination },
  data () {
    return {
      defaultDate: undefined,
      docEmpNm: '',
      docDeptNm: '',
      disabledBtn: true,
      diableDept: true,
      visible: false,
      isJump: false,
      taskTitleList: [],
      relaPaperList: [],
      relaDeptList: [],
      relaEmpList: [],
      rules: {
        teacherTime: [
          { required: true, message: '请选择发布时间', trigger: 'blur' }
        ],
      },
      queryParam: {
        userId: undefined,
        deptId: undefined,
        createDate: undefined,
        teacherTime: undefined,
        startTime: undefined,
        endTime: undefined,
        category: undefined,
      },
      listLoading: false,
      tableData: [],
      total: 0,
      categoryList: [],
      categoryAutocomplete: false,
    }
  },
  watch: {
    'queryParam.userId': {
      handler(newName, oldName) {
        if (newName !== '' && newName !== undefined) {
          this.diableDept = false
        } else {
          this.diableDept = true
        }
      },
      immediate: true,
      deep: true
    },
    'queryParam.deptId': {
      handler(newName, oldName) {
        if (newName !== '' && newName !== undefined) {
          if (this.queryParam.userId !== '' && this.queryParam.userId !== undefined) {
            this.disabledBtn = false
          } else {
            this.disabledBtn = true
          }
        }
      },
      immediate: true,
      deep: true
    }
  },
  created () {
    this.loadAll()
    this.getNowTime()
  },
  methods: {
    getNowTime() {
      var now = new Date()
      var year = now.getFullYear()
      var month = now.getMonth()
      var date = now.getDate()
      month = month + 1
      month = month.toString().padStart(2, '0')
      date = date.toString().padStart(2, '0')
      var defaultDate = `${year}-${month}-${date}`
      this.defaultDate = new Date(defaultDate)
      this.$set(this.queryParam, 'createDate', new Date(defaultDate))
    },
    qryRelaDeparts() {
      this.queryParam.deptId = undefined
      ansApi.usersDeparts({ userId: this.queryParam.userId }).then(res => {
        this.relaDeptList = res.response
      })
    },
    loadAll() {
      userApi.userFilter().then(res => {
        this.relaEmpList = res.response
      })
      taskApi.getTaskCategorys().then(res => {
        this.categoryList = res.response
      })
    },
    submitForm () {
      this.relaEmpList.forEach(item => {
        if (item.id == this.queryParam.userId) {
          this.docEmpNm = item.name
        }
      })
      this.relaDeptList.forEach(item => {
        if (item.id == this.queryParam.deptId) {
          this.docDeptNm = item.name
        }
      })

      const params = {}
      params.userId = this.queryParam.userId
      params.deptId = this.queryParam.deptId
      params.docEmpNm = this.docEmpNm
      params.docDeptNm = this.docDeptNm
      params.category = this.queryParam.category
      // var now = new Date(this.queryParam.createDate)
      // var year = now.getFullYear()
      // var month = now.getMonth()
      // var date = now.getDate()
      // month = month + 1
      // month = month.toString().padStart(2, '0')
      // date = date.toString().padStart(2, '0')
      // params.createDate = year + '-' +  month + '-' + date

      let createDate = this.common.dateFormatYYYY_MM_DD(this.queryParam.createDate)
      params.createDate = createDate

      this.queryParam.startTime = this.queryParam.teacherTime[0]
      this.queryParam.endTime = this.queryParam.teacherTime[1]
      params.startTime = this.queryParam.startTime + ' 00:00:00'
      params.endTime = this.queryParam.endTime + ' 23:59:59'
      ansApi.downloadWord(params).then(() => {
        //
      })
    },
    ...mapActions('exam', { initSubject: 'initSubject' }),
    // 考试类型查询
    categoryQuerySearch(queryString, cb) {
      const categoryList = this.categoryList
      let results = queryString
        ? categoryList.filter(this.createFilter(queryString))
        : categoryList
      results = results.map(item => {
        return {
          value: item
        }
      })
      cb(results)
    },
    createFilter(queryString) {
      return returnJobs => {
        // 改为===0 就是筛选的数据只是首字匹配的列表项，需要包含输入字的所有列表项改为！==-1
        return (
          returnJobs.toLowerCase().indexOf(queryString.toLowerCase()) !== -1
        )
      }
    },
    categoryKeyup(e) {
      if (this.queryParam.category !== '' && this.queryParam.category !== null && this.queryParam.category !== undefined) {
        const data = { keyword: this.queryParam.category}
        taskApi.getTaskCategorys(data).then(res => {
          this.categoryList = res.response
        })
        this.input = e.target.value
      }
    },
    categorySearchHandle() {
      if(this.categoryAutocomplete) {
        this.$refs.categoryAutocompleteRef.activated = true
      }
    },
  },
}
</script>

<style rel="stylesheet/scss" lang='scss'>
.answer3 .el-form-item--medium .el-form-item__label {
  line-height: 36px;
  margin-left: 15px;
}


.answer3 .el-form-item__error {
  color: #ff4949;
  font-size: 12px;
  line-height: 1;
  padding-top: 0px;
  position: absolute;
  top: 100%;
  left: 0;
}

.answer3 .el-form-item--medium .el-form-item__content {
  line-height: 36px;
  text-align: left;
}

.answer3 .el-input--medium .el-input__inner {
  height: 36px;
  line-height: 36px;
  width: 286px;
}

.answer3 .el-form-item {
  margin-bottom: 12px;
}

.answer3 .el-date-editor.el-input, .answer3 .el-date-editor.el-input__inner {
  width: 286px;
}

.answer3 .el-date-editor .el-range-separator {
  display: inline-block;
  height: 100%;
  padding: 0 5px;
  margin: 0;
  text-align: center;
  line-height: 32px;
  font-size: 14px;
  width: 7%;
  color: #303133;
}
</style>
